<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>46、getSnapshotBeforeUpdate举例</title>
  <style>
    .list {
      width: 200px;
      height: 100px;
      background: skyblue;
      overflow: auto;
    }

    .news {
      height: 20px;
    }
  </style>
</head>
<body>
  <div id="test"></div>

  <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://cdn.staticfile.org/prop-types/15.6.1/prop-types.js"></script>

  <script type="text/babel">
    class NewsList extends React.Component{
      state = {
        newsArr: [],
      }

      // 组件挂载
      componentDidMount() {
        setInterval(() => {
          // 获取原状态
          const {newsArr} = this.state
          // 模拟一条新闻
          const news = '新闻' + (newsArr.length + 1)
          // 更新状态
          this.setState({newsArr: [news, ...newsArr]})
        }, 1000)
      }

      // 在更新之前获取快照
      getSnapshotBeforeUpdate() {
        return this.refs.list.scrollHeight
      }

      // 参数：之前的props，之前的state，高度
      componentDidUpdate(preProps, preState, height) {
        // this.refs.list.scrollHeight是现在的高度，减去height之前的高度
        this.refs.list.scrollTop += this.refs.list.scrollHeight - height
      }

      render() {
        return (
          <div className="list" ref='list'>
            {this.state.newsArr.map((n, index) => {
              return <div className="news" key={index}>{n}</div>
            })}
          </div>
        )
      }
    }

    ReactDOM.render(<NewsList />, document.getElementById('test'))
  </script>
</body>
</html>